package io.yx

import java.io.BufferedWriter
import java.io.OutputStreamWriter
import java.io.PrintWriter
import java.io.Writer
import java.net.Socket
import kotlin.system.exitProcess

fun main(args: Array<String>) {

    if (args.size != 2) {
        println("使用 java -jar socketTest.jar host port\n例如: java -jar socketTest.jar 127.0.0.1 8080")
        exitProcess(1)
    }

    if (args[1].toIntOrNull() == null) {
        System.err.println("port is not a integer")
        exitProcess(1)
    }

    val host = args[0]
    val port = args[1].toInt()

    println("正在连接到 $host $port")

    val socket = Socket(host, port)

    println("已连接到 $host $port")

    /**
     * 启动一个虚拟线程监听连接是否断开
     */
    Thread {
        while (!socket.isClosed) {
            Thread.sleep(100)
            continue
        }
        System.err.println("socket已断开!程序退出")
        exitProcess(0)
    }.start()

    /**
     * 启动一个线程用于将接收到的流数据输出
     */
    Thread({
        socket.getInputStream().bufferedReader().use { reader ->
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                println(line)
            }
        }
    }, "receiveTask").start()

    /**
     * 启动一个线程用于从控制台接受输入并发送到服务端
     */
    Thread({
        println("输入内容发送到服务端:")
        socket.getOutputStream().bufferedWriter(Charsets.UTF_8).use { writer ->
            do {
                val line = readln()
                if (line == "exit") {
                    exitProcess(0)
                }
                writer.write(line)
                writer.newLine()
                writer.flush()
            } while (!line.equals("exit", true))
        }
    }, "sendTask").start()

}